var express = require('express');
var path = require('path');

var config = require('./lib/config');
var logger = require('./service/logging').logger;
var methodOverride = require('method-override');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var bodyParser = require('body-parser');
var multer = require('multer');
var errorHandler = require('errorhandler');
var midware_login_admin = require('./routes/midware').midware_login_admin;
var security_interceptor = require('./routes/security_interceptor').request_decide; //api级资源权限验证
var midware_crossdomain = require('./routes/midware').midware_crossdomain;
var midware_login_wechat = require("./routes/midware").midware_login_wechat;
var midware_login_wechat_rest = require("./routes/midware").midware_login_wechat_rest;
var midware_login_wechat_binduser = require("./routes/midware").midware_login_wechat_binduser;
var compression = require('compression');
var app = express();

process.env.NODE_ENV = "development";


var nunjucks = require("nunjucks");
// var midware_login_fw = require('./routes/midware').midware_login_fw;
// var midware_login_rest = require('./routes/midware').midware_login_rest;
nunjucks.configure('views', {
  autoescape: true,
  express: app
});

//-momery unleaked---------
// app.set('trust proxy', 1);

//设置 Session
app.use(session({
  cookie: {maxAge: 60000 * 20 * 6}, //两小时 
  store: new RedisStore({
    // host: config.redis.remote.host,
    // port: config.redis.remote.port,
    host: config.redis.host,
    port: config.redis.port,
    db: 2
  }),
  secret: 'cms@1234',
  resave: true,//是指每次请求都重新设置session cookie，假设你的cookie是10分钟过期，每次请求都会再设置10分钟
  saveUninitialized: true//是指无论有没有session cookie，每次请求都设置个session cookie
}));
app.use(compression());
// app.use(express.compress());
app.set('port', config.listen_port || 80);
app.set('view engine', 'html');
app.set('views', __dirname + '/public');

//app.use(logger('dev'));
//app.use(express.logger("PV`:date`:method`:url`:response-time`:res[Content-Length]"));
app.use(methodOverride());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(multer());
app.use(express.static(path.join(__dirname, 'public')));
// development only
app.use(midware_crossdomain);
if ('development' == app.get('env')) {
    app.use(errorHandler());
}

// app.use(function(err, req, res, next) {
//   var error_msg;
//   var user = '';
//   if (req && req.session && req.session.adminuser) {
//       user = req.session.adminuser.displayname
//   }
//   error_msg = util.inspect({
//       type: "Exception",
//       path: req.path,
//       method: req.method,
//       query: req.query,
//       body: req.body,
//       user: user,
//       error: err.message || err.toString(),
//       stack: err.stack
//   });
//   logger.error(error_msg);
//   console.error(error_msg);
//   res.send(500, {
//       error: err.message || err.toString()
//   });
// });


/*登录操作*/
app.all('/admin_user/login',require('./routes/admin_user').login);
app.all('/admin_user/logout',require('./routes/admin_user').adminuser_logout);

app.all('/api/user/get_users', require('./routes/admin_user').get_users);
app.all('/api/user/get_user', require('./routes/admin_user').get_user);

// 保存用户
app.all('/api/user/save_user', require('./routes/admin_user').save_user);

// 添加用户
app.all('/api/user/add_user', require('./routes/admin_user').add_user);

// 当前用户角色
app.all('/api/user/my_user_role', require('./routes/admin_user').my_user_role);

app.get('/index', function(req, res){
  if(req.session.user){
    res.render('index');
  }
});

app.get('/login', function(req, res){
  console.log('request /login');
  res.render('login');
});

app.get('/*', function(req, res, next){
    var url = req.originalUrl;
    if(url != '/login' && !req.session.user){
      // console.log('not login');
      return res.redirect('login');
    }
    if(req.session.user){
      console.log('redirect /index');
      return res.redirect('/index');
    }
    console.log('request in');
    next();
});

app.listen(app.get('port'), function() {
  console.log('Express server listening on port ' + app.get('port'));
});
